<script setup>
import { onMounted, ref } from 'vue';
import { ElRate, ElForm, ElFormItem, ElInput, ElUpload, ElButton, ElMessage } from 'element-plus';
import axios from 'axios';
import {useRoute, useRouter} from "vue-router";

const route = useRoute();
const router = useRouter();  // 正确初始化 router
const productId = route.params.id;

const car = ref(null);
const getCarById = async () => {
  try {
    const response = await axios.get(`/car/getCarById`, { params: { id: productId } });
    car.value = response.data;
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const formData = ref({
  productId: '',
  rating: 4,
  title: '',
  reviewText: '',
});

// 提交评论表单
const submitReview = async () => {
  formData.value.productId = productId;
  try {
    const response = await axios.post('/reviews/submit', formData.value);
    ElMessage.success('评论提交成功');
    await router.push("/");
  } catch (error) {
    console.error('提交评论失败:', error);
    ElMessage.error('提交评论失败');
  }
};

onMounted(() => {
  getCarById();
});
</script>

<template>
  <div v-if="car">
    <div class="imps">
      <img :src="$urlImage + car.imgs" alt="">
    </div>
  </div>

  <div class="rating-form">
    <el-form :model="formData" label-width="80px">
      <el-form-item label="评分">
        <el-rate v-model="formData.rating" :max="5" allow-half></el-rate>
      </el-form-item>

      <el-form-item label="评论标题">
        <el-input v-model="formData.title" placeholder="请输入评论标题(选填)"></el-input>
      </el-form-item>

      <el-form-item label="评论内容">
        <el-input
            v-model="formData.reviewText"
            type="textarea"
            rows="4"
            placeholder="请输入评论内容(选填)"
            maxlength="200">
          <template #append>
            <span style="font-size: 12px; color: #dd2a2a;">{{ formData.reviewText.length }}/200</span>
          </template>
        </el-input>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" @click="submitReview">提交评价</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.rating-form {
  max-width: 600px;
  margin: 0 auto;
}

.imps {
  display: flex;
  justify-content: center; /* 横向居中 */
  margin-left: 700px;
  align-items: center; /* 纵向居中 */
  max-width: 300px; /* 控制图片的最大宽度 */
  max-height: 300px; /* 控制图片的最大高度 */
  overflow: hidden; /* 防止图片溢出 */
}

.imps img {
  width: 100%; /* 使图片宽度填满容器 */
  height: auto; /* 保持图片的纵横比例 */
}
</style>
